package com.itrip.controller;

import com.itrip.common.DtoUtil;
import com.itrip.common.ErrorCode;
import com.itrip.common.MD5;
import com.itrip.common.ValidationToken;
import com.itrip.dto.Dto;
import com.itrip.entity.ItripUser;
import com.itrip.service.ItripUserService;
import com.itrip.service.SendMailService;
import com.itrip.service.SmsService;
import com.itrip.service.TokenService;
import com.itrip.vo.ItripTokenVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.UUID;

/*
    登录控制器
 */
@RestController
@RequestMapping("/auth/api")
class LoginController {

    @Autowired
    private ItripUserService itripUserService;
    @Resource
    private TokenService tokenService;
    @Resource
    private SmsService smsService;
    @Resource
    private SendMailService sendMailService;

    @GetMapping("/ckusr")
    public Dto ckusr(@RequestParam(value = "name",required = true) String name){

        ItripUser user =  itripUserService.login(name);
        if(user != null){
            //说明用户名存在
            return DtoUtil.returnFail("用户名已存在","000001");
        }
        return DtoUtil.returnSuccess("用户名可用");
    }
    @PostMapping("/dologin")
    public Dto<ItripTokenVO> doLogin(@RequestParam(value = "name",required = true) String userCode,
                                     @RequestParam(value = "password",required = true) String password,
                                     @RequestHeader(value = "user-agent") String userAgent){
        System.out.println(userAgent);
        //TODO 登录功能
        ItripUser loginUser = itripUserService.login(userCode);
        if(loginUser != null){
            //说明存在
            if(loginUser.getUserPassword().equals(MD5.getMd5(password,32).toLowerCase())){
                //登录成功,生成token
                String token = tokenService.generateToken(userAgent,loginUser);
                //保存token
                tokenService.save(token,loginUser);

                ItripTokenVO itVo = new ItripTokenVO(token,
                        Calendar.getInstance().getTimeInMillis() + TokenService.SESSION_TIMEOUT * 1000,
                        Calendar.getInstance().getTimeInMillis());

                return  DtoUtil.returnDataSuccess(itVo);
            }
        }
        return DtoUtil.returnFail("登录失败","1");
    }
    @PostMapping("/registerbyphone")
    public Dto registerByPhone(@RequestBody ItripUser userVo){
        //TODO 手机
        ItripUser user = itripUserService.login(userVo.getUserCode());
        if(user != null){
            //已经被注册
            return DtoUtil.returnFail("手机号已经被注册，请换个手机号码重试！","123456");
        }
        //随机验证码
        String code = String.valueOf(Math.random()).substring(2,8);
        boolean sended = smsService.sendSms(userVo.getUserCode(),code,5);
        if(sended){
            if (saveUser(userVo)) return DtoUtil.returnSuccess();
        }else{
            return DtoUtil.returnFail("短信发送失败,请重试！","123458");
        }
        return DtoUtil.returnFail("注册失败，请重试！","123457");
    }

    @PostMapping("/doregister")
    public Dto doregister(@RequestBody ItripUser userVo){
        //TODO 邮箱
        ItripUser user = itripUserService.login(userVo.getUserCode());
        if(user != null){
            //已经被注册
            return DtoUtil.returnFail("邮箱已经被注册，请换个邮箱重试！","123456");
        }
        //随机验证码
        String code = UUID.randomUUID().toString().replace("-","");
        boolean sended = sendMailService.sendEmail(userVo.getUserCode(),code,5);
        if(sended){
            if (saveUser(userVo)) return DtoUtil.returnSuccess();
        }else{
            return DtoUtil.returnFail("邮件发送失败,请重试！","123458");
        }
        return DtoUtil.returnFail("注册失败，请重试！","123457");
    }

    /**
     * 保存用户
     * @param userVo
     * @return
     */
    private boolean saveUser(ItripUser userVo) {
        ItripUser user;
        user = new ItripUser();
        user.setUserCode(userVo.getUserCode());
        user.setUserName(userVo.getUserName());
        //加密密码
        user.setUserPassword(MD5.getMd5(userVo.getUserPassword(), 32));
        user.setUserType(0L);//自己注册(非QQ，微信注册)
        user.setActivated(0L);//未激活状态
        boolean save = itripUserService.save(user);
        if (save) {
            return true;
        }
        return false;
    }

    @PutMapping("/validatephone")
    public Dto registerByPhone(String user,String code){
        ItripUser dbuser = itripUserService.login(user);
        if(dbuser == null){
            return DtoUtil.returnFail("手机号码不存在，无法激活!","133456");
        }
        boolean validate  = smsService.validate(user,code);
        if(validate){
            //激活状态
            dbuser.setActivated(1L);
            //注册用户的ID就是自己的id
            dbuser.setFlatId(dbuser.getId());
            //更新用户为激活dbuser
            boolean updated = itripUserService.updateById(dbuser);
            if(updated){
                return DtoUtil.returnSuccess();
            }
        }
        return DtoUtil.returnFail("激活失败，请重试!","1334567");
    }
    @PutMapping("/activate")
    public Dto activate(String user,String code){
        ItripUser itripUser = itripUserService.login(user);
        if(itripUser == null){
            return DtoUtil.returnFail("邮件不存在，无法激活!","133456");
        }
        boolean validate  = sendMailService.validate(user,code);
        if(validate){
            //激活状态
            itripUser.setActivated(1L);
            //注册用户的ID就是自己的id
            itripUser.setFlatId(itripUser.getId());
            //更新用户为激活dbuser
            boolean updated = itripUserService.updateById(itripUser);
            if(updated){
                return DtoUtil.returnSuccess();
            }
        }
        return DtoUtil.returnFail("激活失败，请重试!","1334567");
    }
    @GetMapping("/web-activate")
    public String webActivate(String user,String Code){
        Dto dto = activate(user,Code);
        if(dto.getSuccess().equals("true")){
            return "redirect:http://itrip.test.com/#/login";
        }
        return "redirect:http://itrip.test.com";
    }

    @GetMapping("/logout")
    public Dto logout(HttpServletRequest request){
        String tokenString  = request.getHeader("token"); //从请求中获取token
        tokenService.delete(tokenString);
        return DtoUtil.returnSuccess("注销成功");
    }
}
